package com.home.common.filter.cors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Description: 跨域设置
 * Created by 王大宸 on 2020-10-15 21:23
 * Created with IntelliJ IDEA.
 */
@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");      // 1允许任何域名使用
        corsConfiguration.addAllowedHeader("*");      // 2允许任何头
        corsConfiguration.addAllowedMethod("*");      // 3允许任何方法（post、get等）
        corsConfiguration.setAllowCredentials(true);  //这两句不加不能跨域上传文件，

        //支持cookie 跨域
//        corsConfiguration.setAllowCredentials(true);
//        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
//        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
//        corsConfiguration.setAllowedMethods(Arrays.asList("*"));

        //设置时间有效
        corsConfiguration.setMaxAge(86400L);
        return corsConfiguration;
    }

    /***
     * 功能说明：跨域过滤器
     *
     * @author 王大宸
     * @date 2020/10/17 17:49
     * @param
     * @return org.springframework.web.filter.CorsFilter
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }


}
